"use client"
import React, { useState, useEffect } from 'react'
import dayjs from 'dayjs';
import { useDispatch, useSelector } from 'react-redux';
import { Table, ConfigProvider, Space, Button, Modal } from "antd";
import { ProFormDatePicker, ProFormText, QueryFilter } from '@ant-design/pro-components';
import * as asyncfn from '../store/index';
import { shopList_ArrayType, shopList_ObjectType } from '@/component/data';
import Form from "./AddEdit"
export default function page() {
  const dispatch = useDispatch();
  const shopData:shopList_ArrayType = useSelector((state:any) => state.crm.shopList);
  const [title, setTitle] = useState('添加') // 添加/修改功能标题
  const [item, setItem] = useState<any>({}) // 编辑的数据
  const [isModalOpen, setIsModalOpen] = useState(false) // 控制添加/修改框的显示与隐藏
  const showModal = () => {setIsModalOpen(true)}
  const handleOk = () => {setIsModalOpen(false)}
  const handleCancel = () => {setIsModalOpen(false)}

  useEffect(() => {
    dispatch(asyncfn.r_getShangJi() as any)
  }, [dispatch]);
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      width: 50
    },
    {
      title: '商机标题',
      dataIndex: 'title',
      align: 'center'
    },
    {
      title: '关联客户',
      dataIndex: 'Associated_customer',
      align: 'center'
    },
    {
      title: '商机阶段',
      dataIndex: 'stage',
      align: 'center'
    },
    {
      title: '报价记录',
      dataIndex: 'records',
      align: 'center',
      sorter: (a :any, b:any) => a.records - b.records,
      render: (text:number) => {
          return `${text}条`
      }
    },
    {
      title: '报价总金额',
      dataIndex: 'price',
      align: 'center',
      render: (text:number) => {
        return `￥${text.toLocaleString('zh-CN', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })}`
      }
    },
    {
      title: '最后跟进时间',
      dataIndex: 'key',
      align: 'center',
      sorter: (a:any, b:any) => a.key - b.key,
      render: (text:number) => {
          // 可以在这里将时间戳转换为可读的日期格式
          return dayjs(text).format('YYYY-MM-DD')
      }
    },
    {
      title: '未跟进天数',
      dataIndex: 'key',
      align: 'center',
      render: (text:number) => {
        const aprilFirst = new Date();
        const timeDifference = aprilFirst.getTime() - text;
        return Math.ceil(timeDifference / (1000 * 60 * 60 * 24));
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      render: (id:number, record:any) => (
        <div style={{color:'#0079FE'}}>
          {/* 修改当前元素 */}
          <span onClick={()=>{
            setTitle('修改')
            setItem(record)
            showModal()
          }}>修改</span>&nbsp;
          {/* 置顶当前元素 */}
          <span  onClick={()=>{
            let arr:shopList_ArrayType = [...shopData].sort((a:shopList_ObjectType, b:shopList_ObjectType) => {
              return a.id - b.id
            }) // 把数组排序  
            let index = arr.findIndex(item => item.id == id) // 找到当前元素的索引
            let obj = arr[index] // 找到当前元素
            arr.splice(index, 1) // 删除当前元素
            arr=[obj, ...arr] // 把当前元素放在数组的开头
            dispatch(asyncfn.r_Data(arr as any) as any) // 重新赋值给数组
          }}>置顶</span>&nbsp;
          {/* 删除当前元素 */}
          <span onClick={()=>{
            setTitle('删除')
            setItem(record)
            showModal()
            // dispatch(asyncfn.r_DeleteShangJi(id) as any)
          }}> 删除</span>
        </div>
      ),
    }
  ]

  return (
    <div>
      <QueryFilter defaultCollapsed split
        onReset={()=>{
          dispatch(asyncfn.r_getShangJi() as any)
        }}
        onFinish={(v:any)=>{
          v.key? v.key = new Date(v.key).getTime() : undefined;
          dispatch(asyncfn.r_searchShangJi(v) as any)
        }}
      >
        <ProFormText name="title" label="商机标题" />
        <ProFormText name="Associated_customer" label="关联客户" />
        <ProFormText name="stage" label="商机阶段" />
        <ProFormText name="records" label="报价记录" />
        <ProFormText name="price" label="报价总金额" />
        <ProFormDatePicker name="key" label="最后跟进时间" />
      </QueryFilter>
      <Button color="primary" variant="outlined" onClick={()=>{
        setTitle('添加')
        setItem({})
        showModal()
      }}>
        新增
      </Button><br /><br />
      <ConfigProvider
        theme={{
          components: {
            Table: {
              borderColor: '#d9d9d9',
              headerBg: '#ccc',
              headerColor: '#000000',
            }
          }
        }}
      >
        <Table dataSource={shopData} columns={columns as any}
          pagination={{ // 分页配置
            defaultPageSize: 10,
            position: ['bottomLeft'], // 分页位置
          }}
          scroll={{ y: 'min(500px)' }}
          rowKey={'id'}
        />
      </ConfigProvider>
      <Modal
        open={isModalOpen}
        destroyOnClose={true}
        title={title}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Form data={item} handleCancel={handleCancel} title={title} />
      </Modal>
    </div>
  )
}